package com.takeoutOrder.server.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSONArray;
import com.takeoutOrder.common.constant.DishSetmealSConstants;
import com.takeoutOrder.common.core.domain.model.LoginUser;
import com.takeoutOrder.common.exception.ServiceException;
import com.takeoutOrder.common.utils.DateUtils;
import com.takeoutOrder.common.utils.SecurityUtils;
import com.takeoutOrder.framework.web.service.TokenService;
import com.takeoutOrder.server.domain.DishFlavor;
import com.takeoutOrder.server.domain.Setmeal;
import com.takeoutOrder.server.domain.dto.DishDto;
import com.takeoutOrder.server.mapper.DishFlavorMapper;
import com.takeoutOrder.server.mapper.SetmealDishMapper;
import com.takeoutOrder.server.mapper.SetmealMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.takeoutOrder.server.mapper.DishMapper;
import com.takeoutOrder.server.domain.Dish;
import com.takeoutOrder.server.service.IDishService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 菜品管理Service业务层处理
 * 
 * @author linzechen
 * @date 2024-11-23
 */
@Service
public class DishServiceImpl implements IDishService 
{
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    //当前用户信息,此处不能使用静态变量来获取,在系统初始化时获取不到这些数据
    /*static Long userId = SecurityUtils.getUserId();
    static String userName = SecurityUtils.getUsername();
*/
    /**
     * 查询菜品管理
     * 
     * @param id 菜品管理主键
     * @return 菜品管理
     */
    @Override
    public Dish selectDishById(Long id)
    {
        return dishMapper.selectDishById(id);
    }

    /**
     * 查询菜品管理列表
     * 
     * @param dish 菜品管理
     * @return 菜品管理
     */
    @Override
    public List<Dish> selectDishList(Dish dish)
    {
        return dishMapper.selectDishList(dish);
    }

    /**
     * 新增菜品管理
     * 
     * @param dish 菜品管理
     * @return 结果
     */
    @Override
    public int insertDish(Dish dish)
    {
        dish.setCreateTime(DateUtils.getNowDate());
        return dishMapper.insertDish(dish);
    }
@Autowired
private DishFlavorMapper dishFlavorMapper;
    /**
     * 修改菜品管理
     * 
     * @param dishDto 菜品管理
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDish(DishDto dishDto)
    {
        Long userId = SecurityUtils.getUserId();
        String userName = SecurityUtils.getUsername();

        dishDto.setUpdateTime(DateUtils.getNowDate());
        Dish dish = BeanUtil.copyProperties(dishDto, Dish.class);
        dish.setUpdateUser(userId);
        dish.setUpdateBy(userName);
        List<DishFlavor> dishFlavorList = dishDto.getDishFlavorList();
        //先全部删除
        dishFlavorMapper.deleteDishFlavorByDishId(dish.getId());
        //然后批量新增,新增前先判断是否为空,为空就表示删除全部口味数据
        if(!(dishFlavorList==null)){
            dishFlavorList.stream().map(item -> {
            item.setDishId(dishDto.getId());
            item.setCreateBy(userName);
            //格式转换
            String[] parts = item.getValue().split(",\\s*"); // 按照逗号和可选的空格分割
            JSONArray jsonArray = new JSONArray(parts);
            item.setValue(jsonArray.toJSONString());
            return item;
        }).collect(Collectors.toList());
        dishFlavorMapper.insertDishFlavorBatch(dishFlavorList);
        }
        return dishMapper.updateDish(dish);
    }

    /**
     * 批量删除菜品管理
     * 
     * @param ids 需要删除的菜品管理主键
     * @return 结果
     */
    @Override
    public int deleteDishByIds(Long[] ids)
    {
        List<Long> setmealIds=new ArrayList<>();
        for (Long id : ids) {
            List<Long> longs = setmealDishMapper.selectByDishId(id);
            setmealIds.addAll(longs);
        }
        if (setmealIds != null &&!setmealIds.isEmpty()){
            List<Setmeal> setmeals=setmealMapper.selectSetmealByIds(setmealIds);

            if (setmeals!=null && !setmeals.isEmpty()){
                throw new ServiceException("菜品关联启售中的套餐,不能删除");
            }
        }
        return dishMapper.deleteDishByIds(ids);
    }

    /**
     * 删除菜品管理信息
     * 
     * @param id 菜品管理主键
     * @return 结果
     */
    @Override
    public int deleteDishById(Long id)
    {
        return dishMapper.deleteDishById(id);
    }

    @Transactional
    @Override
    public int insertDishDto(DishDto dishDto) {
        //获取dish对象和List<DishFlavor>
        Dish dish = BeanUtil.copyProperties(dishDto, Dish.class);
        List<DishFlavor> dishFlavorList = dishDto.getDishFlavorList();
        //新增的菜品默认为停售,0停售，1起售
        dish.setStatus(DishSetmealSConstants.STATUS_DISABLE);
        dish.setCreateTime(DateUtils.getNowDate());
        int result = dishMapper.insertDish(dish);
        if (result <= 0){
            throw new ServiceException("新增菜品失败");
        }
        //获得到返回的dishId,赋值给flavorList
        //判断是否有口味数据,不为空才插入数据
        if(!(dishFlavorList==null)){
            dishFlavorList.stream().map(item -> {
            item.setDishId(dish.getId());
            //格式转换
            String[] parts = item.getValue().split(",\\s*"); // 按照逗号和可选的空格分割
            JSONArray jsonArray = new JSONArray(parts);
            item.setValue(jsonArray.toJSONString());
            return item;
        }).collect(Collectors.toList());
        dishFlavorMapper.insertDishFlavorBatch(dishFlavorList);
        }
        return result;
    }
    @Autowired
    private TokenService tokenService;

    /**
     * 根据id修改菜品售卖状态
     * @param id
     * @return
     */
    @Override
    @Transactional
    //已完成 等套餐管理模块完成之后,对于修改菜品状态,还要查询是否关联套餐,如果关联套餐则不能停售
    public int changeStatusById(Long id) {

        List<Long> ids =setmealDishMapper.selectByDishId(id);
        if (ids != null &&!ids.isEmpty()){
        List<Setmeal> setmeals=setmealMapper.selectSetmealByIds(ids);

        if (setmeals!=null && !setmeals.isEmpty()){
            throw new ServiceException("菜品关联启售中的套餐,不能停售");
        }
        }
        Dish dish = dishMapper.selectDishById(id);
        Long status=dish.getStatus()==1L?0L:1L;
        return dishMapper.updateStatusById(id,status);
    }
}
